<!--
 * @Author: Chuckie
 * @Email: chuckie@aliyun.com
 * @Date: 2022-11-10 14:35:49
 * @LastEditTime: 2023-06-07 10:03:21
 * @Description: 
 * @FilePath: /base-web/src/views/system/user/list.vue
 *  
-->
<template>
  <div class="app-container scroll-y">
    <!--操作-->
    <div class="page-filter rowSS">
      <!--条件搜索-->
      <el-form ref="refsearchForm" :inline="true" class="demo-searchForm">
        <el-form-item :label="$t('common.search.keywords')">
          <el-input
            v-model="state.filter.keyword"
            :disabled="state.table.loading"
            :placeholder="$t('common.search.placeholder.input')"
          />
        </el-form-item>
      </el-form>

      <!--查询按钮-->
      <el-button type="primary" :disabled="state.table.loading" @click="onSelect">
        <el-icon style="vertical-align: middle">
          <Search />
        </el-icon>
        <span style="vertical-align: middle">{{ $t('common.search.search') }}</span>
      </el-button>
      <el-popconfirm :title="$t('common.message.sure')" @confirm="onRemoves">
        <template #reference>
          <el-button type="danger" :disabled="!multipleSelection.length">
            <el-icon style="vertical-align: middle">
              <Delete />
            </el-icon>
            <span style="vertical-align: middle">{{ $t('common.search.batchDelete') }}</span>
          </el-button>
        </template>
      </el-popconfirm>
      <el-button
        v-if="hasPermission('user:add')"
        type="primary"
        :disabled="state.table.loading"
        @click="router.push('/system/user/detail')"
      >
        <el-icon style="vertical-align: middle">
          <Plus />
        </el-icon>
        <span style="vertical-align: middle">{{ $t('common.search.add') }}</span>
      </el-button>

      <el-button hidden v-print="printObj" type="primary" class="btn">
        <el-icon style="vertical-align: middle">
          <Printer />
        </el-icon>
        <span style="vertical-align: middle">{{ $t('common.search.print') }}</span>
      </el-button>
    </div>

    <!--数据-->
    <div id="print-box" class="page-data">
      <el-table
        ref="multipleTableRef"
        v-loading="state.table.loading"
        :data="state.table.dataSource"
        :border="true"
        stripe
        table-layout="auto"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="36" align="center" fixed />
        <el-table-column type="index" width="50" :label="$t('common.table.serialNumber')" align="center" fixed />
        <el-table-column property="username" :label="$t('systemUser.table.userName')" />
        <el-table-column property="nickname" :label="$t('systemUser.table.nickName')" />
        <el-table-column property="email" :label="$t('systemUser.table.email')" />
        <el-table-column property="phone" :label="$t('systemUser.table.phone')" />
        <el-table-column :label="$t('systemUser.table.sex')">
          <template #default="scope">
            {{ scope.row.sex == 1 ? proxy.$t('systemUser.table.man') : proxy.$t('systemUser.table.woman') }}
          </template>
        </el-table-column>
        <el-table-column property="age" :label="$t('systemUser.table.age')" />
        <el-table-column :label="$t('systemUser.table.userState')">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1">{{ $t('systemUser.table.normal') }}</el-tag>
            <el-tag v-else type="danger">{{ $t('systemUser.table.disabled') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="lastLoginTime" :label="$t('systemUser.table.latestLogin')" />
        <el-table-column fixed="right" :label="$t('common.table.operation.operation')" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="router.push(`/system/user/detail/${scope.row.id}`)">
              {{ $t('common.table.operation.edit') }}
            </el-button>

            <el-button link type="primary" size="small" @click="selectRoleInfo(scope.row.id)">
              {{ $t('systemUser.operation.assignRole') }}
            </el-button>

            <!-- <el-popover placement="right" :width="100" trigger="click">
              <template #reference>
                <el-button style="margin-right: 16px">Click to activate</el-button>
              </template>
              <div  >
                <div   >
                  <el-checkbox-group style="overflow-x: scroll; min-width: 100px;" >
                    <el-checkbox-button @click="updateChecked">
                      a
                    </el-checkbox-button>
                    <el-checkbox-button @click="updateChecked">
                      avvvv
                    </el-checkbox-button>
                    <el-checkbox-button @click="updateChecked">
                      ad
                    </el-checkbox-button>
                    <el-checkbox-button @click="updateChecked">
                      aee
                    </el-checkbox-button>
                    <el-checkbox-button @click="updateChecked">
                      a
                    </el-checkbox-button>
                    <el-checkbox-button @click="updateChecked">
                      a
                    </el-checkbox-button>
                    <el-checkbox-button @click="updateChecked">
                      a
                    </el-checkbox-button>
                    <el-checkbox-button @click="updateChecked">
                      a
                          </el-checkbox-button>

                        </el-checkbox-group>
                      </div>


                    </div>

                  </el-popover> -->
            <el-popconfirm :title="$t('common.message.sure')" @confirm="onRemove([scope.row.id])">
              <template #reference>
                <el-button link type="danger" size="small">{{ $t('common.table.operation.delete') }}</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-pagination">
      <el-pagination
        v-model:currentPage="state.pagination.pageNum"
        v-model:page-size="state.pagination.pageSize"
        :page-sizes="[20, 50, 100]"
        small="small"
        :disabled="state.table.loading"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.pagination.total"
        @current-change="onSelect"
        @size-change="onSelect"
      />
    </div>

    <el-dialog
      v-model="state.dialogVisible"
      :title="$t('systemUser.operation.assignRole')"
      width="30%"
      style="width: 400px"
    >
      <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; row-gap: 20px">
        <el-checkbox
          v-for="(name, code) in state.role.all"
          @click="(e) => updateRole(e, code)"
          v-model="state.role.checked[code]"
          :checked="state.role.checked[code]"
        >
          {{ name }}
        </el-checkbox>
      </div>

      <template #footer>
        <span class="dialog-footer"></span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElTable } from 'element-plus'
import { Search, Delete, Plus, Printer } from '@element-plus/icons-vue'
import { BaseUser, select, create, update, remove } from './api/base-user'
import { select as selectRole } from './api/base-role'
import { selectRoleIdByUserId, add as addRole } from './api/base-user'
import { hasPermission } from '../../../utils/tools'

const { proxy }: any = getCurrentInstance()
const router = useRouter()

const state = reactive({
  filter: {
    keyword: null
  },
  table: {
    loading: true,
    dataSource: Array<BaseUser>()
  },
  pagination: {
    pageNum: 1,
    pageSize: 20,
    total: 0
  },

  role: {
    all: {},
    checked: {}
  },
  currentUserId: 0,
  dialogVisible: false
})

const printObj = reactive({
  id: 'print-box',
  popTitle: '配置页眉标题',
  previewTitle: '预览标题',
  previewPrintBtnlabel: '预览结束，开始打印',
  beforeOpenCallback(vue: any) {
    console.log('打开前')
  },
  openCallback(vue: any) {
    console.log('执行了打印')
  },
  closeCallback(vue: any) {
    console.log('关闭了打印工具')
  }
})

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<BaseUser[]>([])

const onSelectionChange = (records: BaseUser[]) => {
  multipleSelection.value = records
}

const onSelect = async () => {
  state.table.loading = true
  const data = await select({ pageNum: state.pagination.pageNum, pageSize: state.pagination.pageSize, ...state.filter })
  state.table.dataSource = data.data.items

  state.pagination.total = data.data.total
  state.table.loading = false
}

const onUpdate = async (entity: BaseUser) => {
  const data = await update(entity)
  onSelect()
}

const onRemoves = async () => {
  onRemove(multipleSelection.value.map((item: BaseUser) => item.id || ''))
}

const onRemove = async (ids: Array<string>) => {
  const data = await remove(ids)
  proxy.$message({ message: proxy.$t('common.message.deleteSuccessfully'), type: 'success' })
  onSelect()
}

const selectAllRole = async () => {
  const data = await selectRole({ page: 1, pageSize: 10000 })
  data.data.items.map((ele) => {
    state.role.all[ele.id] = ele.roleName
  })
  data.data.items.map((ele) => {
    state.role.checked[ele.id] = false
  })
}

const selectRoleInfo = async (id, isopen = true) => {
  state.currentUserId = id

  if (isopen) {
    state.dialogVisible = isopen
  }

  const data = await selectRoleIdByUserId(id)
  for (let key in state.role.checked) {
    state.role.checked[key] = false
  }

  data.data.map((ele) => (state.role.checked[ele.id] = true))
  if (!isopen) proxy.$message({ message: '成功', type: data.code === 20000 ? 'success' : 'error' })
}

const updateRole = async (e, code) => {
  if (e.target.tagName == 'INPUT') {
    state.role.checked[code] = !state.role.checked[code]
    const roleIdsArr = <any>[]
    for (const key in state.role.checked) {
      if (state.role.checked[key]) {
        roleIdsArr.push(key)
      }
    }
    const result = await addRole({ roleIds: roleIdsArr, userId: String(state.currentUserId) })
    const success = '2,200,20000'
    if (success.includes(result.code)) {
      selectRoleInfo(state.currentUserId, false)
    }
  }
}

onMounted(() => {
  onSelect()
  selectAllRole()
})
</script>

<style scoped lang="scss"></style>
